package org.zasadnyy.redlions.players.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.zasadnyy.redlions.players.server.dao.Dao;
import org.zasadnyy.redlions.players.server.model.PlayerObject;
import org.zasadnyy.redlions.players.server.persistance.PmfFactory;

import com.google.appengine.api.datastore.Key;

public class JdoPlayersDao implements Dao<PlayerObject> {

	private PersistenceManagerFactory pmfInstance = PmfFactory.get();

	@Override
	public PlayerObject getById(Key id) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			return pm.getObjectById(PlayerObject.class, id);
		} finally {
			pm.close();
		}
	}

	@Override
	public List<PlayerObject> getAll() {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			List<PlayerObject> players = new ArrayList<PlayerObject>();
			Extent<PlayerObject> extent = pm.getExtent(PlayerObject.class,
					false);
			for (PlayerObject player : extent) {
				players.add(player);
			}
			extent.closeAll();

			return players;
		} finally {
			pm.close();
		}
	}

	@Override
	public Key addOrEdit(PlayerObject player) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			pm.makePersistent(player);
			pm.refresh(player);
		} finally {
			pm.close();
		}
		return player.getId();
	}

	@Override
	public void deleteById(Key id) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			pm.deletePersistent(pm.getObjectById(PlayerObject.class, id));
		} finally {
			pm.close();
		}
	}

}
